<template>
    <el-row style="margin: 10px 10px 20px 10px; text-size-adjust: 10px; padding: 10px;">
        <el-col :span="9">
            <span style="padding-right: 10px;">名称:</span>
            <el-input v-model="fromData.name" style="width: 240px"/>
        </el-col>
        <el-col :span="9">
            <span style="padding-right: 10px;">层级:</span>
            <el-select v-model="fromData.level" clearable placeholder="Select" style="width: 240px">
                <el-option v-for="item in optionsLevel" :key="item.value" :label="item.name" :value="item.value" />
            </el-select>
            <!-- <el-input v-model="fromData.level" style="width: 240px" placeholder="Pick a date" :suffix-icon="Calendar" /> -->
        </el-col>
        <el-col :span="2">
            <el-button type="primary" @click="menuList()">查询</el-button>
        </el-col>
        <el-col :span="2">
            <el-button type="success" @click="add()">新增</el-button>
        </el-col>
    </el-row>
    <el-table :data="tableData" style="width: 100%" :stripe="true" :border="true" v-loading="loading">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column align="center" :label="dataTable.title" v-for="dataTable in table" :min-width="dataTable.width"
            :prop="dataTable.dataIndex">
            <template #default="scope" v-if="dataTable.type === 'date'">
                <span v-if="dataTable.dataIndex === 'createTime'">
                    {{ dayjs(scope.row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
                </span>
                <span v-if="dataTable.dataIndex === 'updateTime'">
                    {{ scope.row.updateTime }}
                </span>
            </template>
            <template #default="scope" v-if="dataTable.dataIndex === 'Operations'">
                <el-button size="small" v-if="scope.row.name === 'test123'">
                    查看
                </el-button>
                <el-button size="small" type="danger">
                    Delete
                </el-button>
            </template>
        </el-table-column>
    </el-table>
    <!-- <el-tree
      style="max-width: 600px"
      :data="menuData"
      show-checkbox
      node-key="id"
      default-expand-all
      :expand-on-click-node="false"
      :render-content="renderContent"
    /> -->
    <div class="custom-tree-node">
        <el-tree
        style="max-width: 600px"
        :data="menuData"
        default-expand-all
        node-key="id"
        :expand-on-click-node="false"
        >
        <template #default="{ node ,data}">
            <div class="custom-tree-node">
            <span>{{ data.name }}</span>
            <div style="padding-left: 100px;">
                <el-button type="primary" link @click="edit(data)">
                edit
                </el-button>
                <el-button
                style="margin-left: 4px"
                type="danger"
                link  @click="deleteMenu(data.id)">
                删除
                </el-button>
            </div>
            </div>
        </template>
        </el-tree>
    </div>

    <el-dialog v-model="addVisible" :title="!editVisible?'新增菜单':'编辑菜单'" width="500" align-center @close="!editVisible?addClose():updateClose()">
        <el-form label-width="auto" :model="fromAddData" style="max-width: 300px" :rules="rules" :ref="!editVisible?'addRuleFormRef':'updateRuleFormRef'">
            <el-form-item label="名称" label-position="left" prop="name">
                <el-input v-model="fromAddData.name" />
            </el-form-item>
            <el-form-item label="层级" label-position="left" prop="level" v-if="!editVisible">
                <el-select v-model="fromAddData.level" clearable placeholder="Select" style="width: 240px" @change="levelChange(fromAddData.level)">
                    <el-option v-for="item in optionsLevel" :key="item.value" :label="item.name" :value="item.value"/>
                </el-select>
            </el-form-item>
            <el-form-item label="父级" label-position="left" prop="parentId" v-if="!editVisible">
                <el-select v-model="fromAddData.parentId" clearable placeholder="Select" style="width: 240px" :disabled="parentIdDisabled">
                    <el-option v-for="item in parentData" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="排序" label-position="left" prop="sort">
                <el-input-number v-model="fromAddData.sort" :min="1" :max="10" />
            </el-form-item>
            <el-form-item label="路由地址" label-position="left" prop="routerUrl">
                <el-input v-model="fromAddData.routerUrl" style="width: 100px" placeholder="/list" />
            </el-form-item>
            <el-form-item label="图标" label-position="left" prop="icon">
                <el-select-v2
                    v-model="fromAddData.icon"
                    :options="iconListOptions"
                    style="width: 70px">
                        <template #default ="{ item }">
                        <div>
                            <el-icon>
                                   <component :is="item.value"></component>
                            </el-icon>
                        </div>
                        </template>
                        <template #label="{ label, value }" >
                            <el-icon>
                                   <component :is="value"></component>
                            </el-icon>
                        </template>
                </el-select-v2>   
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="addVisible = false">Cancel</el-button>
                <el-button type="primary" @click="!editVisible?fromAdd():fromUpdate()">
                    Confirm
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script setup lang="ts">
import { ref, onMounted ,reactive} from 'vue'
import { FormInstance, FormRules ,ElMessage, ElMessageBox} from 'element-plus'
import dayjs from 'dayjs'
import menu from '../api/menu/menu.js'

const loading = ref(true);
const tableData = ref();
const fromData = ref({});
const fromAddData = ref({});
const addVisible = ref(false)
const editVisible = ref(false)
const parentIdDisabled = ref(true)
const iconList = ref([])
const iconListOptions = ref([])
const addRuleFormRef = ref<FormInstance>()
const updateRuleFormRef = ref<FormInstance>()
const parentData = ref([{}])
const menuData = ref([])
const optionsLevel = [
    {
        name: "一级",
        value: 1
    },
    {
        name: "二级",
        value: 2
    },
    {
        name: "三级",
        value: 3
    }];

const table = [
    {
        title: '姓名',
        width: 120,
        type: "string",
        dataIndex: 'name'
    },
    {
        title: '创建时间',
        width: 200,
        type: "date",
        dataIndex: 'createTime'
    },
    {
        title: '删除状态',
        width: 120,
        type: "string",
        dataIndex: 'deleteFlag'
    },
    {
        title: '修改时间',
        width: 200,
        type: "date",
        dataIndex: 'updateTime'
    }, {
        title: '操作',
        width: 50,
        type: "string",
        dataIndex: "Operations"
    }
];

// 自定义校验规则
const validateParentId = (rule: any, value: any, callback: any) => {
    if(fromAddData.value.level ===1){
        callback()
    }else if(fromAddData.value.parentId != undefined){
        callback()
    }else{
        callback(new Error('父级不能为空'))
    }
}

const rules = reactive<FormRules<typeof ruleForm>>({
  name: [
    { required: true, message: '名称不能为空', trigger: 'blur' },
  ],
  icon: [
    {
      required: true,
      message: '图标不能为空',
      trigger: 'change',
    },
  ],
  level: [
    { required: true, message: '层级必填', trigger: 'blur' },
  ],
  sort: [
    {
        required: true,
        message: '排序不能为空',
        trigger: 'change',
    }
  ],
  parentId: [
    {
        validator: validateParentId, trigger: 'blur'
    }
  ],
  routerUrl: [
  {
        required: true,
        message: '路由地址不能为空',
        trigger: 'change',
    }
  ]
});

onMounted(() => {
    const icon = localStorage.getItem('iconList')
    if(icon){
        iconList.value = icon.split(',')
    }
    for(let index = 0; index < iconList.value.length; index++) {
        const element = iconList.value[index];
        iconListOptions.value.push({value: element,label: element})   
    }
    menuList({})
    getAllList()
});

const getAllList =() =>{
    menu.getAllList().then((value) => {
        menuData.value = value.data;
        console.log("menuData",menuData.value);
    })
};

const menuList = (data) => {
    loading.value = true
    menu.menuList(data).then((value) => {
        console.log("menu", value);
        // loading.value = false
        tableData.value = value.data
        setTimeout(() => {
            loading.value = false
        }, 1000)
    })
};

const add = () => {
    addVisible.value = true
}
const edit = (node) =>{
    fromAddData.value = {...node}
    addVisible.value = true
    editVisible.value = true
    
}
const deleteMenu = (id) =>{
    ElMessageBox.confirm(
            '您确定要删除吗?',
            'Warning',
            {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            })
    .then(() => {
        menu.deleteMenu({id : id}).then((value)=>{
          getAllList()
          ElMessage({
                type: 'success',
                message: '操作成功',
          })
        })
    })
    .catch(() => {
        ElMessage({
            type: 'info',
            message: 'Delete canceled',
        })
    })
}

const fromAdd = () => {
    addRuleFormRef.value.validate((valid) => {
    console.log(valid);
    if (valid) {
            console.log("fromAddData",fromAddData.value);
                menu.addMenu({
                    name: fromAddData.value.name,
                    parentId: fromAddData.value.parentId,
                    icon: fromAddData.value.icon,
                    sort: fromAddData.value.sort,
                    routerUrl: fromAddData.value.routerUrl
                    }).then((value) =>{
                    addVisible.value =false
                    getAllList()
                })
    } else {
      console.log('error submit!')
    }
  })
}
const fromUpdate =() =>{
    console.log("update",updateRuleFormRef.value);
    
    updateRuleFormRef.value.validate((valid) => {
    console.log(valid);
    if (valid) {
        menu.updateMenu({
                    name: fromAddData.value.name,
                    id: fromAddData.value.id,
                    icon: fromAddData.value.icon,
                    sort: fromAddData.value.sort,
                    routerUrl: fromAddData.value.routerUrl
                    }).then((value) =>{
                    addVisible.value =false
                    getAllList()
        })
    }else {
      console.log('error submit!')
    }
  })
}
const addClose =() =>{
    parentIdDisabled.value =true;
    fromAddData.value = {};
    addRuleFormRef.value.resetFields();
}
const updateClose = ()=>{
    editVisible.value = false;
    fromAddData.value = {};
    updateRuleFormRef.value.resetFields();
}
const levelChange = (item) =>{
    if(item===1){
        parentData.value = [{}]
        parentIdDisabled.value =true
        fromAddData.value.parentId = undefined
    }else{
        if(item){
            menu.getLevelList(item-1).then((data)=>{
                parentData.value = data.data
                parentIdDisabled.value =false
           })
        }
    }
}

</script>
<style>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>